package network1;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpClient {
    private DatagramSocket socket=null;
    private int ServePort;
    private String ServeIP;
    public UdpClient(String ServeIP,int ServePort){
        try {
            socket=new DatagramSocket();
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
        this.ServePort=ServePort;
        this.ServeIP=ServeIP;
    }
    public void start() throws UnknownHostException {
        System.out.println("客户端启动");
        Scanner scanner =new Scanner(System.in);
        while(true){
            System.out.print("请输入:");
            String msg=scanner.next();
            DatagramPacket respPacket=new DatagramPacket(msg.getBytes(),0,msg.getBytes().length, InetAddress.getByName(ServeIP),
                    ServePort);
            try {
                socket.send(respPacket);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            DatagramPacket responPacket=new DatagramPacket(new byte[4096],4096);
            try {
                socket.receive(responPacket);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            String respon=new String(responPacket.getData(),0,responPacket.getLength());
            System.out.println(respon);
        }
    }

    public static void main(String[] args) {
        UdpClient udpClient=new UdpClient("127.0.0.1",9090);
        try {
            udpClient.start();
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }

    }
}
